package com.health.trans.processor.listener;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.health.trans.kit.ThreadMonitor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ItemWriteListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author nqlz
 */
@Slf4j
@Component
public class StepItemWriteListener implements ItemWriteListener {
    public static ThreadLocal<DateInfo> dateInfoLocal = new ThreadLocal<>();

    @Setter
    @Getter
    @Accessors(chain = true)
    public static class DateInfo {
        private Date start;
        private Date end;
        private Boolean isLog = false;

        public String getTime() {
            return "writer 执行时间：" + ThreadMonitor.getTime(start, end);
        }

        public void printLog() {
            if (end == null) {
                end = new Date();
            }
            log.info(getTime());
            isLog=true;
        }
    }

    @Override
    public void beforeWrite(List items) {
        MyItemReadListener.DateInfo dateInfo = MyItemReadListener.dateInfoLocal.get();
        if (dateInfo != null) {
            dateInfo.setEnd(new Date());
        }
        if (dateInfoLocal.get() != null) {
            while (!dateInfoLocal.get().isLog) {
                ThreadUtil.sleep(3, TimeUnit.SECONDS);
            }
            dateInfoLocal.get().setStart(new Date()).setIsLog(false);
        } else {
            dateInfoLocal.set(new DateInfo().setStart(new Date()).setIsLog(false));
        }
    }

    @Override
    public void afterWrite(List items) {
        MyItemReadListener.DateInfo dateInfo = MyItemReadListener.dateInfoLocal.get();
        if (dateInfo != null) {
            dateInfo.setStart(new Date());
        }
        if (dateInfoLocal.get() != null) {
            dateInfoLocal.get().setEnd(new Date()).setIsLog(false);
        } else {
            dateInfoLocal.remove();
            ExceptionUtil.wrapAndThrow(new RuntimeException("出错啦"));
        }
    }

    @Override
    public void onWriteError(Exception exception, List items) {
       log.info("ItemWriteListener - onWriteError:",exception);
    }
}
